package com.sw.openssl

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Base64
import android.util.Log
import com.sw.openssl.databinding.ActivityMainBinding
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Example of a call to a native method
        binding.sampleText.text = stringFromJNI()

        var text = "openssl加密、解密测试字符串"
        Log.e("openssl JNI", "对比  \"$text\"  MD5、AES加解密:");
        Log.e("openssl JNI", "JAVA MD5: ${MD5(text)}");
        Log.e("openssl JNI", "OPENSSL MD5: ${jniMD5(text)}");
        var encodeBytes = aesEncode(text.toByteArray())
        Log.e("openssl JNI", "AES加密: ${String(Base64.encode(encodeBytes, Base64.NO_WRAP))}");
        Log.e("openssl JNI", "AES解密: ${String(aesDecode(encodeBytes))}");

    }

    fun MD5(text: String): String {
        try {
            //获取md5加密对象
            val instance: MessageDigest = MessageDigest.getInstance("MD5")
            //对字符串加密，返回字节数组
            val digest: ByteArray = instance.digest(text.toByteArray())
            var sb = StringBuffer()
            for (b in digest) {
                //获取低八位有效值
                var i: Int = b.toInt() and 0xff
                //将整数转化为16进制
                var hexString = Integer.toHexString(i)
                if (hexString.length < 2) {
                    //如果是一位的话，补0
                    hexString = "0" + hexString
                }
                sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }

        return ""
    }

    /**
     * A native method that is implemented by the 'openssl_cmake' native library,
     * which is packaged with this application.
     */
    external fun stringFromJNI(): String
    external fun jniMD5(text: String): String
    external fun aesEncode(data: ByteArray): ByteArray
    external fun aesDecode(data: ByteArray): ByteArray

    companion object {
        // Used to load the 'openssl_cmake' library on application startup.
        init {
            System.loadLibrary("openssl_cmake")
        }
    }
}